<template>
  <!-- 巡检表单 -->
  <a-modal
    v-model:open="visible"
    title="巡检表单"
    @ok="handleOk"
    class="addStation"
    destroyOnClose
    :width="1430"
    @cancel="cancel"
    centered
  >
    <div ref="tableRef">
      <a-table
        :dataSource="tableData"
        :columns="columns"
        :pagination="false"
        bordered
        class="formTable"
        :loading="tableLoading"
      >
        <template #headerCell="{ column }">
          <template v-if="column.key === 'remark'">
            <span>
              备注与照片
              <a-tooltip>
                <template #title>
                  <p>
                    若该运维内容检查结果全部正常，则只需上传整体照片和照片标题；
                  </p>
                  若检查结果存在异常，则需要描述清楚异常内容，上传异常照片并填写对应和照片标题</template
                >
                <ExclamationCircleOutlined />
              </a-tooltip>
            </span>
          </template>
        </template>

        <template #bodyCell="{ column, record, index }">
          <!-- 检查结果 -->
          <template v-if="column.key === 'result'">
            <a-radio-group
              v-if="record.key !== NEW_INSPECTION_ORDER.ORTHER"
              v-model:value="record.result"
              @change="changeResult(record)"
              :disabled="!showEditBtn"
            >
              <a-radio :value="0">正常</a-radio>
              <a-radio :value="1">异常</a-radio>
              <a-radio :value="2">不适用</a-radio>
            </a-radio-group>
          </template>

          <!-- 备注与照片 -->
          <template v-if="column.key === 'remark'">
            <a-form
              :model="record.remark"
              layout="inline"
              :labelCol="labelCol"
              :ref="(res) => setFormRef(res, index)"
              :disabled="!showEditBtn"
            >
              <!-- 如果是其他补充内容，不可编辑情况下，假如无内容则不显示 -->
              <a-form-item
                v-if="showErrorMsg(record.group)"
                :label="
                  record.group === NEW_INSPECTION_ORDER.ORTHER_GROUP
                    ? '补充内容'
                    : '异常情况描述'
                "
                name="errorMsg"
                :rules="[
                  {
                    required:
                      record.group !== NEW_INSPECTION_ORDER.ORTHER_GROUP &&
                      showEditBtn,
                    trigger: 'blur',
                    validator: errorMsgRule(
                      record.remark.errorMsg,
                      record.group
                    ),
                  },
                ]"
                style="margin-bottom: 20px"
              >
                <a-textarea
                  v-model:value="record.remark.errorMsg"
                  maxlength="150"
                  show-word-limit
                  :placeholder="
                    record.group === NEW_INSPECTION_ORDER.ORTHER_GROUP
                      ? '请输入补充内容'
                      : '请输入异常情况描述'
                  "
                  style="width: 250px"
                  :rows="4"
                />
              </a-form-item>
              <a-form-item
                :label="
                  showErrorMsg(record.group) &&
                  record.group !== NEW_INSPECTION_ORDER.ORTHER_GROUP
                    ? '上传异常照片'
                    : '上传图片'
                "
                :name="`tableData.${index}.remark.imgList.${i}.imgUrl`"
                :rules="[
                  {
                    required: isValidImg(record) && showEditBtn,
                    trigger: 'blur',
                    validator: imgUrlRule(record.remark?.imgList, record.group),
                  },
                ]"
              >
                <div class="uploadImgContent">
                  <a-upload
                    v-if="showEditBtn"
                    :action="uploadAction"
                    :auto-upload="true"
                    :headers="headers"
                    multiple
                    :showUploadList="false"
                    :before-upload="beforeUpload"
                    :class="showEditBtn ? '' : 'disabledUpload'"
                    @change="(res) => handleUpload(res, index)"
                  >
                    <div class="uploadContent">
                      <loading-outlined v-if="loading"></loading-outlined>
                      <plus-outlined v-else></plus-outlined>
                      <div class="ant-upload-text">上传</div>
                    </div>
                  </a-upload>
                  <a-form-item
                    v-for="(item, i) in record.remark?.imgList"
                    :key="i"
                    class="uploadImg"
                    :name="`tableData.${index}.remark.imgList.${i}.imgTitle`"
                    :rules="[
                      {
                        // required: true,
                        trigger: 'blur',
                        validator: imgTitleRule(
                          tableData[index].remark.imgList[i].imgTitle
                        ),
                      },
                    ]"
                  >
                    <!-- <img :src="item.imgUrl" /> -->
                    <div class="imgBlock">
                      <a-image
                        :src="item.imgUrl"
                        style="width: 114px; max-height: 120px"
                      />
                      <PictureOutlined
                        v-if="!item.imgUrl"
                        style="
                          font-size: 50px;
                          color: #999;
                          vertical-align: middle;
                        "
                      />
                      <CloseCircleOutlined
                        v-if="showEditBtn"
                        @click="delImg(item, record.index)"
                        class="closeIcon"
                      />
                    </div>
                    <a-input
                      v-model:value="item.imgTitle"
                      placeholder="请输入照片标题"
                      class="desc"
                      :key="i"
                    />
                    <!-- <span v-else class="desc" :title="item.imgTitle">{{
                    item.imgTitle
                  }}</span> -->
                  </a-form-item>
                </div>
              </a-form-item>
            </a-form>
          </template>
        </template>
      </a-table>
    </div>
    <div class="formTips">
      填表说明：
      <p style="margin-top: 10px">
        1、巡检工作宜在在无风沙，且天气晴朗干燥时开展；风沙季节，或当周围环境中相对湿度大于95%时，请勿开启储能集成系统内设备柜门；
      </p>
      <p>
        2、明确巡检的目的为：全面检查，发现问题，暴露问题，为及时消缺提供依据，进一步保障系统稳定运行；
      </p>
      <p>
        3、配备巡检工器具，人员须按清单完整、仔细检查，认真填写，巡检人员对结果真实性负责，严禁弄虚作假；
      </p>
      <p>4、红外测温应选在充电/放电的高功率时间段；</p>
      <p>5、检查结果栏，选择“正常”或者“异常”，若不适用，选择“不适用”；</p>
      <p>
        6、单个项目的巡检间隔周期原则上不应长于30天，项目数量多、人员/工器具安排不具备条件等特殊情况时，间隔周期最多不应长于60天；
      </p>
    </div>
    <template #footer>
      <div class="footerBar">
        <a-button
          v-if="showEditBtn"
          key="submit"
          type="primary"
          :loading="loading"
          @click="handleSubmit(1)"
          class="greenBtn"
          >暂存</a-button
        >
        <a-button
          v-if="showEditBtn"
          key="submit"
          type="primary"
          :loading="loading"
          @click="handleSubmit(0)"
          >确认</a-button
        >
        <a-button key="back" @click="cancel">关闭</a-button>
        <a-button
          key="back"
          class="filterBtn greenBtn"
          @click="savePdfFun"
          v-if="props.rowData.state === 4 || props.rowData.state === 5"
          >导出</a-button
        >
      </div>
    </template>
  </a-modal>
</template>
<script setup>

import storage from "@/utils/storage"
import { NEW_INSPECTION_ORDER, WORK_ORDER_TYPE } from "@/constants/workOrder"
import { cloneDeep, pickBy } from "lodash-es"
import savePdf from "@/utils/savePdf"
const $api = inject("$api")
const props = defineProps({
  inspectionFormVisible: {
    type: Boolean,
    default: false,
  },
  rowData: {
    type: Object,
  },
  stationtList: {
    type: Array,
  },
})
const visible = ref(props.inspectionFormVisible)
const emits = defineEmits(["update:inspectionFormVisible", "getOrderList"])
const fileList = ref([])
const userInf = storage.getItem("USER_INFO")
const headers = ref({
  Authorization: "Bearer " + userInf.access_token,
})
const tableLoading = ref(false)
const showEditBtn = computed(
  () =>
    // inspectionEdit (巡检表单是否可编辑 1：是 0：否)
    props.rowData.inspectionEdit === 1
)
watch(
  () => props.inspectionFormVisible,
  async (val) => {
    visible.value = val
    if (val) {
      initForm()
    }
  }
)
const labelCol = { style: { width: "105px" } }
const form = ref({
  stationId: undefined,
  date: undefined,
  description: undefined,
  attachmentFileId: undefined,
})
const formFefList = ref([])
const setFormRef = (el, index) => {
  // 这里赋值每个表单的ref数组
  if (
    index > -1 &&
    !formFefList.value.some((item) => item.index === index) &&
    NEW_INSPECTION_ORDER.TABLE_FORM_KEY.includes(index)
  ) {
    formFefList.value.push({
      index,
      el,
    })
  }
}
let tableData = ref([])
const columns = ref([
  {
    title: "编号",
    dataIndex: "number",
    key: "number",
    width: 70,
    resizable: true,
    align: "center",
    customCell: (record, index, column) => {
      if (record.group === "A") {
        if (index === 0) {
          return { rowSpan: 6 }
        }
        if (index >= 1 && index <= 6) {
          return {
            rowSpan: 0,
          }
        }
      }
      if (record.group === "B") {
        if (index === 6) {
          return { rowSpan: 16 }
        }
        if (index > 6 && index < 22) {
          return {
            rowSpan: 0,
          }
        }
      }
      if (record.group === "C") {
        if (index === 22) {
          return { rowSpan: 6 }
        }
        if (index > 22 && index <= 28) {
          return {
            rowSpan: 0,
          }
        }
      }
      if (record.group === "D") {
        if (index === 28) {
          return { rowSpan: 2 }
        }
        if (index > 28 && index <= 30) {
          return {
            rowSpan: 0,
          }
        }
      }
      if (record.group === "E") {
        if (index === 30) {
          return { rowSpan: 2 }
        }
        if (index > 30 && index <= 32) {
          return {
            rowSpan: 0,
          }
        }
      }
      if (record.group === "G") {
        if (index === 30) {
          return { rowSpan: 2 }
        }
        if (index > 30 && index <= 32) {
          return {
            rowSpan: 0,
          }
        }
      }
      if (
        record.group === "F" ||
        record.group === "G" ||
        record.group === "H" ||
        record.group === "I" ||
        record.group === "J"
      ) {
        if (index === 33) {
          return { rowSpan: 11 }
        }
        if (index > 33 && index <= 44) {
          return {
            rowSpan: 0,
          }
        }
      }
      if (record.group === "K") {
        if (index === 44) {
          return { rowSpan: 5 }
        }
        if (index > 44 && index <= 49) {
          return {
            rowSpan: 0,
          }
        }
      }
    },
  },
  {
    title: "运维内容",
    dataIndex: "type",
    key: "type",
    width: 200,
    resizable: true,
    align: "center",
    customCell: (record, index, column) => {
      if (record.group === "A") {
        if (index === 0) {
          return { rowSpan: 6 }
        }
        if (index >= 1 && index <= 6) {
          return {
            rowSpan: 0,
          }
        }
      }
      if (record.group === "B") {
        if (index === 6) {
          return { rowSpan: 16 }
        }
        if (index > 6 && index < 22) {
          return {
            rowSpan: 0,
          }
        }
      }
      if (record.group === "C") {
        if (index === 22) {
          return { rowSpan: 6 }
        }
        if (index > 22 && index <= 28) {
          return {
            rowSpan: 0,
          }
        }
      }
      if (record.group === "D") {
        if (index === 28) {
          return { rowSpan: 2 }
        }
        if (index > 28 && index <= 30) {
          return {
            rowSpan: 0,
          }
        }
      }
      if (record.group === "E") {
        if (index === 30) {
          return { rowSpan: 2 }
        }
        if (index > 30 && index <= 32) {
          return {
            rowSpan: 0,
          }
        }
      }
      if (record.group === "G") {
        // 10KV进线柜
        if (index === 33) {
          return { rowSpan: 3 }
        }
        if (index > 33 && index <= 36) {
          return {
            rowSpan: 0,
          }
        }
      }
      if (record.group === "J") {
        // 10kV开关柜（通用）
        if (index === 38) {
          return { rowSpan: 6 }
        }
        if (index > 38 && index <= 44) {
          return {
            rowSpan: 0,
          }
        }
      }
      if (record.group === "K") {
        if (index === 44) {
          return { rowSpan: 5 }
        }
        if (index > 44 && index <= 49) {
          return {
            rowSpan: 0,
          }
        }
      }
      // 其他补充
      if (index === 49) {
        if (record.group === "Z") {
          return { colSpan: 3 }
        } else {
          return { colSpan: 1 }
        }
      }
    },
  },
  {
    title: "巡查内容",
    dataIndex: "info",
    key: "info",
    width: 420,
    resizable: true,
    align: "center",
    customCell: (record, index, column) => {
      if (index === 49) {
        return { colSpan: 0 }
      } else {
        return { colSpan: 1 }
      }
    },
    className: "cellOverflow",
  },
  {
    title: "检查结果",
    dataIndex: "result",
    key: "result",
    width: 270,
    resizable: true,
    align: "center",
    customCell: (record, index, column) => {
      if (index === 49) {
        return { colSpan: 0 }
      } else {
        return { colSpan: 1 }
      }
    },
  },
  {
    title: "备注与照片",
    dataIndex: "remark",
    key: "remark",
    width: 400,
    resizable: true,
    align: "center",
    customCell: (record, index, column) => {
      if (record.group === "A") {
        if (index === 0) {
          return { rowSpan: 6 }
        }
        if (index >= 1 && index <= 6) {
          return {
            rowSpan: 0,
          }
        }
      }
      if (record.group === "B") {
        if (index === 6) {
          return { rowSpan: 16 }
        }
        if (index > 6 && index < 22) {
          return {
            rowSpan: 0,
          }
        }
      }
      if (record.group === "C") {
        if (index === 22) {
          return { rowSpan: 6 }
        }
        if (index > 22 && index <= 28) {
          return {
            rowSpan: 0,
          }
        }
      }
      if (record.group === "D") {
        if (index === 28) {
          return { rowSpan: 2 }
        }
        if (index > 28 && index <= 30) {
          return {
            rowSpan: 0,
          }
        }
      }
      if (record.group === "E") {
        if (index === 30) {
          return { rowSpan: 2 }
        }
        if (index > 30 && index <= 32) {
          return {
            rowSpan: 0,
          }
        }
      }
      if (record.group === "G") {
        if (index === 30) {
          return { rowSpan: 2 }
        }
        if (index > 30 && index <= 32) {
          return {
            rowSpan: 0,
          }
        }
      }
      if (
        record.group === "F" ||
        record.group === "G" ||
        record.group === "H" ||
        record.group === "I" ||
        record.group === "J"
      ) {
        if (index === 33) {
          return { rowSpan: 11 }
        }
        if (index > 33 && index <= 44) {
          return {
            rowSpan: 0,
          }
        }
      }
      if (record.group === "K") {
        if (index === 44) {
          return { rowSpan: 5 }
        }
        if (index > 44 && index <= 49) {
          return {
            rowSpan: 0,
          }
        }
      }
    },
  },
])
const cancel = async () => {
  emits("update:inspectionFormVisible", false)
  for (let i = 0; i < formFefList.value.length; i++) {
    try {
      await formFefList.value[i].el.clearValidate()
    } catch (error) {
      console.warn(`[ 表单${i}] 验证清除失败:`, error)
    }
  }
  form.value = {
    stationId: undefined,
    date: undefined,
    description: undefined,
    attachmentFileId: undefined,
  }
  fileList.value = []
}
const showErrorMsg = (group) => {
  // 同组内是否有异常
  if (group === "Z") {
    // 补充说明直接返回
    return true
  }
  if (group === "G") {
    const groupList = ["G", "H", "I", "J"] // 第七组的校验合并一起
    const Gdata = tableData.value.filter((item) =>
      groupList.includes(item.group)
    )
    const hasError = Gdata.some((item) => item.result === 1)
    return hasError
  } else {
    const hasError = tableData.value
      .filter((item) => item.group === group)
      .some((item) => item.result === 1)
    return hasError
  }
}
const imgTitleRule = (title, group) => {
  return (rule, value) => {
    if (!title) {
      return Promise.reject("请填写照片标题")
    }
    return Promise.resolve()
  }
}
const errorMsgRule = (data, group) => {
  return (rule, value) => {
    if (!data && group !== "Z") {
      return Promise.reject("请填写异常信息")
    }
    return Promise.resolve()
  }
}
const loading = ref(false)
// @param {number} inspectionTempSaveFlag  1：暂存 0：保存
const handleSubmit = async (status) => {
  let validArr = []
  if (status === 1) {
    // 暂存不需要校验
    validArr = [true]
  } else {
    for (let i = 0; i < formFefList.value.length; i++) {
      try {
        await formFefList.value[i].el.validate()
        validArr[i] = true
      } catch (error) {
        validArr[i] = false
        console.warn(`[ 表单${i}] 验证失败:`, error)
      }
    }
  }

  if (validArr.every((item) => item)) {
    const paramsTableData = handlePrefixTableData()
    const inspectionFormSaveAttach = cloneDeep(paramsTableData)
      .map((item) => item.remark?.imgList)
      .filter(Boolean)
      .flat()
      .map((item) => item.imgId)
      .join(",") // 上传的图片的id（后端要求传）

    const params = {
      id: props.rowData.id,
      inspectionTempSaveFlag: status, // 1：暂存 0：保存
      inspectionForm: JSON.stringify(paramsTableData),
      type: WORK_ORDER_TYPE.INSPECTION,
      inspectionFormSaveAttach,
      inspectionFormDelAttach: inspectionFormDelAttach.value?.join(","),
    }

    loading.value = true
    const res = await $api.editWorkorder(params)
    loading.value = false
    if (res && res.code === 0) {
      message.success(status === 1 ? "暂存成功" : "保存成功")
      cancel()
      emits("getOrderList")
    }
  }
}
const uploadAction = async (val) => {
  return `${$api.uploadAction().url}`
}
const changeResult = async (row) => {
  // 校验当前组group
  // await formFefList.value[LETTER_MAPPING[row.group]].el.validate()
}
const isValidImg = (row) => {
  const onlyNotApplicable = tableData.value
    .filter((item) => item.group === row.group)
    .every((item) => item.result === 2)
  // 图片校验条件：
  // 1. 有 正常 或 异常 的情况，而非全部都是 不适用
  // 2. showSaveBtn 为 true
  // 3. 包含于需要校验的组 NEED_VALID_GROUP
  return (
    !onlyNotApplicable &&
    NEW_INSPECTION_ORDER.NEED_VALID_GROUP.includes(row.group)
  )
}
const imgUrlRule = (data, group) => {
  const onlyNotApplicable = tableData.value
    .filter((item) => item.group === group)
    .every((item) => item.result === 2)
  return (rule, value) => {
    if (
      !onlyNotApplicable &&
      !data.some((item) => item.imgUrl) &&
      NEW_INSPECTION_ORDER.NEED_VALID_GROUP.includes(group)
    ) {
      return Promise.reject("请上传图片")
    }
    return Promise.resolve()
  }
}
const handleUpload = (res, index) => {
  if (res.file?.response?.code === 0) {
    tableData.value[index].remark.imgList.push({
      imgId: res.file.response.data.id,
      imgUrl: res.file.response.data.url,
      imgTitle: "",
      ...res.data,
    })
    // 找到对应的表单，进行校验
    formFefList.value.find((item) => item.index === index)?.el?.validate()
  }

  if (res.file?.status === "error") {
    tableData.value[index].remark.imgList.push({
      imgUrl: "",
      imgTitle: "",
      ...res.data,
    })
  }
}
const inspectionFormDelAttach = ref([])
const delImg = (item, index) => {
  tableData.value[index].remark.imgList = tableData.value[
    index
  ].remark.imgList.filter((img) => img !== item)
  inspectionFormDelAttach.value.push(item.imgId) // 记录下删除的图片id，用于传给后端
}
// 初始化表格表单数据
const initForm = async () => {
  tableData.value = cloneDeep(NEW_INSPECTION_ORDER.INSPECTION_TABLE) // 先获取本地表格常量数据
  tableLoading.value = true
  const res = await $api.workOrderDetail(props.rowData.id)
  if (res?.code === 0 && res?.data?.inspectionForm) {
    // 如果有数据，进行初始化操作，若无则直接用常量
    let formData = JSON.parse(res.data.inspectionForm)

    // 获取表单所有图片id，获取url
    const iconFileIds = formData
      .map((item) => item.remark?.imgList)
      .filter(Boolean)
      .flat()
      .map((item) => item.imgId)
    const urlRes = await $api.fileFindByIds(iconFileIds)
    tableLoading.value = false

    formData = formData.map((item) => {
      if (item?.remark) {
        return {
          ...item,
          remark: {
            ...item.remark,
            imgList: item.remark.imgList.map((img) => {
              const matchUrl = urlRes.data.find((url) => url.id === img.imgId)
              return {
                ...img,
                imgUrl: matchUrl?.url,
              }
            }),
          },
        }
      }
      return {
        ...item,
      }
    })
    await nextTick()
    // 根据已保存信息处理数据
    for (const item of tableData.value) {
      const matchData = formData?.find((data) => data.key === item.key)
      item.result = matchData?.result
      item.remark = matchData?.remark
    }
  } else {
    tableLoading.value = false
  }
}
/* const res = await fetch(
  "https://ngp-cloud.oss-cn-shenzhen.aliyuncs.com/prod/2025-06-06/a6b73838d7e597a3890f.png"
)
console.log(res) */
const handlePrefixTableData = () => {
  // 处理巡检表单提交数据
  // 保存表单时，只需要传 key result remark 这三个字段
  const prefixTableData = cloneDeep(tableData.value).map((item) => {
    if (item.remark && item.remark.imgList) {
      const modifiedImgList = item.remark.imgList.map((img) => {
        const { imgUrl, ...rest } = img
        return rest
      })
      return {
        key: item.key,
        result: item.result,
        remark: {
          ...item.remark,
          imgList: modifiedImgList,
        },
      }
    } else {
      return {
        key: item.key,
        result: item.result,
      }
    }
  })
  return prefixTableData
}
//导出巡检工单
const tableRef = ref(null)
const savePdfFun = async () => {
  let list = [tableRef.value]
  savePdf.savePDF(list, `${props.rowData.companyName}巡检工单`)
}
</script>

<style lang="less" scoped>
.form {
  padding: 0 40px;
  margin-top: 30px;
}
.formInput,
.formSelect {
  width: 250px;
}
.footerBar {
  text-align: center;
  margin-top: 30px;
}
.addEquipUpload {
  .anticon-eye {
    display: none;
  }
}
.formTips {
  margin-top: 20px;
  line-height: 1.5;
}
.uploadImgContent {
  .desc {
    display: block;
    margin-top: 10px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }
}
.uploadImg {
  width: 120px;
  height: 180px;
  display: inline-block;
  margin-right: 10px;
  position: relative;
  img {
    width: 120px;
    height: 120px;
    border-radius: 4px;
  }
  .closeIcon {
    display: none;
    position: absolute;
    color: #fff;
    top: 5px;
    right: 5px;
    width: 15px;
    height: 15px;
    cursor: pointer;
  }
  &:hover {
    .closeIcon {
      display: block;
    }
  }
}
.uploadContent {
  width: 120px;
  height: 120px;
  margin-right: 10px;
  border: 1px dashed #606060;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  display: inline-block;
  vertical-align: top;
  transition: all 0.3s;
  text-align: center;
  &:hover {
    border: 1px dashed #1668dc;
    .anticon {
      color: #1668dc;
    }
  }
  .anticon {
    font-size: 28px;
    color: #8c939d;
    height: 120px;
    text-align: center;
  }
}
.uploadImgContent {
  width: 267px;
  text-align: left;
  .desc {
    display: block;
    margin-top: 10px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }
}
.formTable {
  ::v-deep(.ant-table-cell) {
    white-space: pre-wrap;
  }
  ::v-deep(.cellOverflow) {
    white-space: pre-wrap;
    text-align: left !important;
  }
  ::v-deep(.ant-form-item-explain-error) {
    text-align: left;
  }
}
.disabledUpload {
  pointer-events: none;
}
.imgBlock {
  width: 120px;
  height: 120px;
  line-height: 120px;
  border: 1px solid #606060;
  border-radius: 4px;
  text-align: center;
}
</style>
